<template>
  <div :class="className">
    <!-- style -->
    <div v-html="css"></div>
    <!--文章静态-->
    <div>
      <div id="article">
        <!--:style="{ backgroundColor: datas.article_bg }"-->
        <div class="tab_box" v-if="(datas.get_style == 1 || datas.get_style == 3) && datas.show_tab && !tabcontrol">
          <ul class="tab_list" v-if="categories">
            <van-tabs v-model="active"
                      swipeable
                      @change="onClick"
                      :background="datas.article_tab_bg"
                      :title-active-color="datas.title_active_color"
                      :color="datas.title_active_color"
                      :title-inactive-color="datas.title_color"
                      id="tab">
              <van-tab title="全部分类" v-if="datas.get_style == 1"
                       :name="0"
                       class="tabChild"></van-tab>
              <van-tab :title="item.name"
                       v-for="(item,i) in categories"
                       :name="String(item.id)" :key='i'
                       class="tabChild"></van-tab>
            </van-tabs>
          </ul>
        </div>

        <!--自动获取-->
        <template v-if="Number(datas.get_number) > 0 && datas.list && (datas.get_style == 1 || datas.get_style == 3)">
          <div class="article-list one" :class="plugin_active ? 'member-article-list' : ''" v-for="(item, index) in list" :key="index" @click.stop.prevent="item.type == 1?(item.playStatus?pause(index):startPlayOrPause(item, index)):gotoArticle(item)">
            <div class="miain">
              <!-- 样式一图片 -->
              <div v-if="datas.article_style == 1" class="image-style1">
                <div class="posimg" v-if="item.type == 1" @click.stop="startPlayOrPause(item, index)">
                  <van-icon name="pause" v-if="item.playStatus" @click.stop="pause(index)" />
                  <van-icon name="play" v-else @click.stop="startPlayOrPause(item, index)"/>
                </div>
                <img :src="item.thumb || emptyImage" alt=""/>
              </div>
              <div class="content">
                <div class="title" style="-webkit-box-orient: vertical;">
                  <span class="pay-money" v-if="item.has_one_article_pay || item.is_pay == 1">付费</span><span>{{item.title}}</span>
                </div>
                <div style="flex: 1;" ></div>
                <div class="flex f-12" style="flex-direction: column;" v-if="datas.show_donate && item.donate">
                  <div>本人捐赠数量：{{ item.donate.member_donate }}</div>
                  <div>总捐赠数量：{{ item.donate.donate_total }}</div>
                </div>
                <div class="message" v-if="!item.type">
                  <div class="author">{{item.author}}</div>
                  <div class="time">{{item.created_at || item.virtual_at}}</div>
                </div>
                <div class="title_v" v-else>
                  <div class="time">
                    <span>播放{{ item.virtual_audio_views }}次</span>
                    <span class="audio-seconds">{{ item.audio_seconds }}</span>
                  </div>
                  <div class="audioShare" @click.stop="shareTap">
                    <i class="iconfont icon-zb_all_share"></i>
                    <span>分享</span>
                  </div>
                </div>
              </div>
              <!-- 样式二图片 -->
              <div v-if="datas.article_style == 2" class="image-style2">
                <div class="posimg" v-if="item.type == 1" @click.stop="startPlayOrPause(item, index)">
                  <van-icon name="pause" v-if="item.playStatus" @click.stop="pause(index)" />
                  <van-icon name="play" v-else @click.stop="startPlayOrPause(item, index)"/>
                </div>
                <img :src="item.thumb || emptyImage" alt=""/>
              </div>
            </div>
            <audio
              :id="'audio' + index"
              :ref="'audio' + index"
              @pause="onPause(index)"
              @play="onPlay(index)"
              @timeupdate="onTimeupdate($event,index)"
              @loadedmetadata="onLoadedmetadata($event,index)"
              @ended="endedMethod"
              controls="controls"
              style="display: none;"
              :src="item.audio_link"
            >
              您的浏览器不支持 audio 标签！
            </audio>
            <div class="slider" v-if="item.type == 1 && sliderShow && index == playInd">

              <div class="sliderBox">
                <van-slider @input='handleTouchStart($event,index)' v-model="sliderTime" bar-height="6px" active-color="#f3a5a5" inactive-color="#f5f5f5" v-if="item.type == 1 && index == playInd" >
                  <template #button>
                    <div class="custom-button"></div>
                  </template>
                </van-slider>
              </div>
              <div class="iconclose" @click.stop="tapClose">
                <i class="iconfont icon-close11"></i>
              </div>
            </div>
          </div>
        </template>

        <!--手动获取-->
        <template v-if="datas.list && datas.get_style == 2">
          <div class="article-list" v-for="(item,index) in datas.list" :key="index" @click.stop.prevent="item.type == 1?(item.playStatus?pause(index):startPlayOrPause(item, index)):gotoArticle(item)">
            <div class="miain">
              <!-- 样式一图片 -->
              <div v-if="datas.article_style == 1" class="image-style1">
                <div class="posimg" v-if="item.type == 1" @click.stop="startPlayOrPause(item, index)">
                  <van-icon name="pause" v-if="item.playStatus" @click.stop="pause(index)" />
                  <van-icon name="play" v-else @click.stop="startPlayOrPause(item, index)"/>
                </div>
                <img :src="item.thumb || emptyImage" alt=""/>
              </div>
              <div class="content">
                <div class="title" style="-webkit-box-orient: vertical;">
                  <span class="pay-money" v-if="item.is_pay == 1">付费</span><span>{{item.title}}</span>
                </div>
                <div style="flex: 1;" ></div>
                <div class="flex f-12" style="flex-direction: column;" v-if="datas.show_donate && item.donate">
                  <div>本人捐赠数量：{{ item.donate.member_donate }}</div>
                  <div>总捐赠数量：{{ item.donate.donate_total }}</div>
                </div>
                <div class="message" v-if="!item.type">
                  <div class="author" v-if="item.author">{{item.author}}</div>
                  <div class="time">{{item.created_at || item.virtual_at}}</div>
                </div>
                <div class="title_v" v-else>
                  <div class="time">
                    <span>播放{{ item.virtual_audio_views }}次</span>
                    <span class="audio-seconds">{{ item.audio_seconds }}</span>
                  </div>
                  <div class="audioShare" @click.stop="shareTap">
                    <i class="iconfont icon-zb_all_share"></i>
                    <span>分享</span>
                  </div>
                </div>
              </div>
              <!-- 样式二图片 -->
              <div v-if="datas.article_style == 2" class="image-style2">
                <div class="posimg" v-if="item.type == 1" @click.stop="startPlayOrPause(item, index)">
                  <van-icon name="pause" v-if="item.playStatus" @click.stop="pause(index)" />
                  <van-icon name="play" v-else @click.stop="startPlayOrPause(item, index)"/>
                </div>
                <img :src="item.thumb || emptyImage" alt=""/>
              </div>
            </div>
            <audio
              :id="'audio' + index"
              :ref="'audio' + index"
              @pause="onPause(index)"
              @play="onPlay(index)"
              @timeupdate="onTimeupdate($event,index)"
              @loadedmetadata="onLoadedmetadata($event,index)"
              @ended="endedMethod"
              controls="controls"
              style="display: none;"
              :src="item.audio_link"
            >
              您的浏览器不支持 audio 标签！
            </audio>
            <div class="slider" v-if="item.type == 1 && sliderShow && index == playInd">
              <div class="sliderBox">
                <van-slider @input='handleTouchStart($event,index)' v-model="sliderTime" bar-height="6px" active-color="#f3a5a5" inactive-color="#f5f5f5" v-if="item.type == 1 && index == playInd" >
                  <template #button>
                    <div class="custom-button"></div>
                  </template>
                </van-slider>
              </div>
              <div class="iconclose" @click.stop="tapClose">
                <i class="iconfont icon-close11"></i>
              </div>
            </div>
          </div>
        </template>

        <div v-if="datas.list && datas.list.length <= 0 && datas.get_style == 2" style="padding: 15px; text-align: center;">
          暂无设置文章
        </div>

        <div v-if="!noNotice && (datas.get_style == 1 || datas.get_style == 3)">
          <div
            style="width: 100%; height: 40px; line-height: 40px; text-align: center;"
            v-if="isLoadMore"
            @click="getMoreData"
          >{{ $i18n.t("加载更多") }}</div>
          <div
            style="width: 100%; height: 40px; line-height: 40px; text-align: center;"
            v-if="lastIndex == index && allLoaded"
          >{{ $i18n.t("没有更多了") }}~</div>
        </div>
        <div v-if="noNotice" style="text-align: center;">
          <img
            style="width: 5rem; padding: 2rem 0; display: inherit;"
            src="../../assets/images/blank.png"
            alt=""
            v-if="fun.isTextEmpty(list)"
          />
        </div>

      </div>
    </div>

  </div>
</template>

<script>
import emptyImage from '../../assets/images/new_diy/image.png';
import { Toast } from "vant";
// 自定义样式
const css = function () {

  if(this.datas.article_bg) {
    // 确保数据已传入
    const {
      article_bg,
      article_tab_bg,
      title_color,
      title_active_color,
      text_size,
      margin_top,
      margin_bottom,
      margin_left,
      margin_right,
      box_radius
    } = this.datas;

    return `
        .component-${this.id} .article-list {
            background-color: ${article_bg};
            margin-top: ${margin_top}px;
            margin-bottom: ${margin_bottom}px;
            margin-left: ${margin_left}px;
            margin-right: ${margin_right}px;
            border-radius: ${box_radius}px;
        }

        .component-${this.id} .article-list .title {
            font-size: ${text_size || 14}px;
            line-height: ${(text_size + 2) || 16}px;
            height: ${((text_size + 2)*2) || 32}px;
        }

        .component-${this.id} .nav-bgimage {
            background-color: ${article_tab_bg || "#fff"};
        }

        .component-${this.id} .nav-li {
            color: ${title_color};
        }

        .component-${this.id} .nav-li.nav-selected {
            color: ${title_active_color};
            border-bottom: solid  2px ${title_active_color };
        }
    `;
  }

};

export default {
  data() {
    return {
      emptyImage,

      active: "",
      class_id: "0",
      list: [],
      categories: [],
      isLoadMore: false,
      page: 1,
      total_page: 0,
      pageSize: 12,
      noNotice: false,
      allLoaded: false, // 全部数据已经加载完成
      sliderTime: 0,
      playInd: null,
      currentTime: '',
      postStart: false,
      sliderShow:false
    };
  },
  props: ["id", "datas", "tabcontrol", 'lastIndex', 'index', "plugin_active","isBottom"],
  computed: {
    css() {
      return "<style>" + css.call(this) + "</style>";
    },
    className() {
      const name = ["component-wrapper", `component-${this.id}`];
      return name;
    },
  },
  mounted() {
    if(this.datas.get_style == 1 || this.datas.get_style == 3) {
      this.initData();
      //获取数据
      this.getNetData(this.datas);
    }else {
      this.isLoadMore = false;
      this.allLoaded = true;
    }
  },
  watch: {
    isBottom:function(nval,oval) {
      if(nval){
        if(this.lastIndex == this.index){
          this.getMoreData();
        }
      }
    },
  },
  methods: {
    initData() {
      this.page = 1;
      this.total_page = 0;
      this.isLoadMore = true;
      this.allLoaded = false;
      this.list = [];
      this.sliderShow = false;
    },
    // 拖动
    handleTouchStart(e, i) {
      this.$refs[`audio${i}`][0].currentTime = parseInt((this.datas.get_style == 2?this.datas.list[i]:this.list[i]).maxTime * (e / 100));
      this.$refs[`audio${i}`][0].play()
    },
    onLoadedmetadata(res, i) {
      console.log(this.list)
        if(res.target.duration){
          this.$set((this.datas.get_style == 2?this.datas.list[i]:this.list[i]), 'maxTime', parseInt(res.target.duration))
        }

    },
    onTimeupdate(res, i) {
      this.currentTime = res.target.currentTime;
      let time = parseInt(this.currentTime / (this.datas.get_style == 2?this.datas.list[i]:this.list[i]).maxTime * 100);
      if (time >= 100) {
        this.sliderTime = 100;
      } else {
        this.sliderTime = time;
      }

    },
    async startPlayOrPause(item, i) {
      if(item.is_pay == 1 || item.has_one_article_pay){
        let result =  await this.checkNoticeVideo(item.id);
        if(result == 0){
          //未付费
          this.$router.push(this.fun.getUrl("payList", { id: item.id }));
          return
        }
      }
      let check = await this.checkPrivilege(item.id)
      if(check.result == 0){
        Toast(check.msg);
        return
      }
      if (this.playInd != i) {
        this.postStart = false;
      }
      if(!this.sliderShow) this.sliderShow = true;
      this.playInd = i;
      console.log(this.datas.list)
      let info = this.datas.get_style == 2?this.datas.list:this.list;
      for (let k = 0; k < info.length; k++) {
        if (k == i) {
          if (this.$refs[`audio${i}`][0].onplay) {
            this.pause(i);
          } else {
            this.play(i);
          }
        } else {
          // this.$refs[`audio${k}`][0].load();
          this.$set(this.datas.get_style == 2?this.datas.list[k]:this.list[k], 'playStatus', false)
          this.$refs[`audio${k}`][0].pause();
        }
      }
    },
    checkPrivilege(id){
      return new Promise((resolve, reject)=>{
        $http.get("plugin.article.api.article.get-article", { article_id: id },).then(
          response => {
            if (response.result == 1) {
              resolve(response)
            }else{
              resolve(response)
            }
          },
          function (response) {
            console.log(response);
          }
        );
      })
    },
    // 播放结束
    endedMethod() {
      console.log('endedMethod')
      this.postStart = false;
    },
    // 播放音频
    play(i) {
      this.$refs[`audio${i}`][0].play();
      this.startPostMethod();
    },
    // 暂停音频
    pause(i) {
      this.$refs[`audio${i}`][0].pause();
      this.postStart = true;
    },
    // 当音频暂停
    onPause(i) {
      this.$set(this.datas.get_style == 2?this.datas.list[i]:this.list[i], 'playStatus', false)
    },
    onPlay(i) {
      this.$set(this.datas.get_style == 2?this.datas.list[i]:this.list[i], 'playStatus', true)
    },
    shareTap() {
      this.$dialog.alert({ message: "请点击右上角微信分享" });
    },
    toEssay() {
      this.$router.push(this.fun.getUrl("payEssay"));
    },
    tapClose(){
      this.sliderShow =false;
    },
    startPostMethod() {
      let json = { article_id: '' }
      if(this.datas.get_style == 2){
        json.article_id = this.datas.list[this.playInd].id;
      }else{
        json.article_id = this.list[this.playInd].id;
      }
      if (this.postStart == false) {
        console.log('没有暂停')
        $http.get("plugin.article.api.article.clickAudioViews", json,).then(
          response => {
            if (response.result == 1) {
              console.log('完成',response)
              if(this.datas.get_style == 2){
                this.$set(this.datas.list[this.playInd], 'virtual_audio_views', response.data.virtual_audio_views)
              }else{
                this.$set(this.list[this.playInd], 'virtual_audio_views', response.data.virtual_audio_views)
              }
            }
          },
          function (response) {
            console.log(response);
          }
        );
      } else {
        console.log('暂停过 postStart = true')
      }
    },
    //获取数据
    getNetData(data) {
      if(data) {
        if(data.cate && data.cate[0]) {
          this.class_id = data.cate[0].id;
          this.active = data.cate[0]?String(data.cate[0].id):"0";
          if(this.datas.get_style == 1){
            this.class_id = 0;
            this.active =0;
          }
        }
        this.noNotice = false;
        this.total_page = data.list.last_page;
        this.pageSize = data.list.per_page;
        this.isLoadMore = true;
        if(this.total_page<=1) {
          this.isLoadMore = false;
          this.allLoaded = true;
        }
        if(data.list.data.length > this.datas.get_number) {
          data.list.data.splice(this.datas.get_number, data.list.data.length-this.datas.get_number);
          this.isLoadMore = false;
          this.allLoaded = true;
        }
        this.list = data.list.data;
        if(data.cate) {
          this.categories = data.cate;
          if (data.cate.length <= 0) {
            this.noNotice = true;
          }
        }

        return;
      }
      let json = { category_id: this.class_id, page: 1, pageSize: 12,
        show_audio: this.datas.show_audio,is_decorate: true };
      $http.get("plugin.article.api.article.get-articles", json, "获取中").then(
        response => {
          if (response.result == 1) {
            this.noNotice = false;
            this.total_page = response.data.articles.last_page;
            this.pageSize = response.data.articles.per_page;
            this.isLoadMore = true;
            if(this.total_page<=1) {
              this.isLoadMore = false;
              this.allLoaded = true;
            }
            if (response.data.categories.length <= 0) {
              this.noNotice = true;
            }

            if(response.data.articles.data.length > this.datas.get_number) {
              response.data.articles.data.splice(this.datas.get_number, response.data.articles.data.length-this.datas.get_number);
              this.isLoadMore = false;
              this.allLoaded = true;
            }

            this.list = response.data.articles.data;
            // this.categories = response.data.categories;
          } else {
            this.noNotice = true;
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },

    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.page >= this.total_page || this.list.length > this.datas.get_number) {
        console.log("getMoreData", this.total_page);
      } else {
        this.page = this.page + 1;
        let json = { category_id: this.class_id, page: this.page, pageSize: this.pageSize,show_audio: this.datas.show_audio,is_decorate: true};
        $http
          .get("plugin.article.api.article.get-articles", json, "加载中")
          .then( (response)=> {
            if (response.result === 1) {

              this.total_page = response.data.articles.last_page;
              if(this.page < this.total_page) {
                this.isLoadMore = true;
              }else {
                this.allLoaded = true;
              }

              this.list = this.list.concat(response.data.articles.data);
              if(this.list.length > this.datas.get_number) {
                this.list.splice(this.datas.get_number,this.list.length-this.datas.get_number);
                this.isLoadMore = false;
                this.allLoaded = true;
              }
              this.$emit('setLoadMore', this.isLoadMore);
            } else {
              this.page = this.page - 1;
              this.isLoadMore = false;
              this.allLoaded = true;
            }
          },
          function(response) {
            // error callback
          }
          );
      }
    },

    gotoArticle(item) {
      if(item.type == 1){
        // this.$router.push(this.fun.getUrl("VoiceDetail", { article_id: item.id }));
        return
      }else{
        this.$router.push(this.fun.getUrl("articleContent", { id: item.id }));
      }
    },
    checkNoticeVideo(aid){
      return new Promise((resolve, reject) => {
        $http.get("plugin.article-pay.api.index.paid", {article_id:aid},).then(
          response => {
            resolve(response.result)
          },
          function (response) {
            reject(response)
          }
        );
      })

    },
    onClick(index, title) {
      this.initData();
      this.class_id = index;
      this.getNetData();
    }
  },
};
</script>

<style lang="scss" scoped>
  // 默认
  .component-wrapper {
    width: 100%;
    text-align: left;
  }

  #article {
    .nav {
      display: flex;
      align-items: center;
      height: 40px;
      white-space: nowrap;
      flex-wrap: nowrap;
      box-sizing: content-box;

      .nav-li {
        flex: 1;
        min-width: 20%;
        text-align: center;

        .nav-lis {
          display: inline-block;
          line-height: 40px;
        }
      }
    }

    .scroll {
      overflow-x: scroll;
    }

    .slider {
      width: 100%;
      margin-top: 0.625rem;
      display: flex;
      align-items: center;
      cursor: default;
      user-select: none;
      outline: none;

      .sliderBox {
        flex: 1;
      }

      .iconclose {
        margin-left: 0.9375rem;
        flex-shrink: 0;
      }
    }

    .custom-button {
      width: 13px;
      height: 13px;
      color: #fff;
      text-align: center;
      background-color: #ee0a24;
      border-radius: 100px;
    }

    .article-list {
      padding: 0.625rem;

      .miain {
        display: flex;
        position: relative;
      }

      .image-style1 {
        width: 7.5rem;
        height: auto;
        border-radius: 8px;
        margin-right: 15px;
        position: relative;
        margin-right: 0.75rem;
        flex-shrink: 0;
        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }

      .content {
        flex:1;
        display: flex;
        text-align: left;
        flex-direction: column;
        justify-content: space-between;
        overflow: hidden;

        .title {
          font-size: .9375rem;
          line-height: 1.2rem;
          height: auto;
          color: #00001c;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          font-weight: 500;

          .pay-money {
            display: inline-block;
            width: 1.75rem;
            height: 1rem;
            line-height: 1rem;
            border-radius: 0.25rem;
            background-color: #f69a30;
            text-align: center;
            font-size: .625rem;
            color: #fff;
            margin-right: 0.3125rem;
          }
        }

        .title_v {
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: #867e7e;
          font-size: .3125rem;
          .audio-seconds{
            margin-left: 0.5625rem;
          }

          .audioViews,
          .audioShare {
            display: flex;
            align-items: center;
            margin-right: 0.325rem;
            color: #3b3b4a;
            font-size: .6875rem;
          }
          .icon-zb_all_share{
            color: #3b3b4a;
            font-size: .9375rem !important;
          }
          .time {
              display: flex;
              align-items: center;
              margin-right: 0.325rem;
              line-height: 22px;
              font-size: .6875rem;
              color: #aaaab3;
          }

          .iconfont {
            font-size: 1.3rem;
            margin-right: 0.125rem;
          }

          .icon-seller-time {
            font-size: 1.1rem;
            margin-top: 1px;
          }

          .icon-fontclass-bofang1 {
            font-size: 0.7rem;
          }
        }

        .message {
          display: flex;
          align-items: center;
          font-size: .6875rem;
          color: #aaaab3;
          .author {
            text-overflow: ellipsis;
            overflow: hidden;
            margin-right: 0.7813rem;
            white-space: nowrap;
            flex: 1;
          }
        }
      }

      .image-style2 {
        margin-left: 0.9375rem;
        flex-shrink: 0;
        width: 7.5rem;
        height: auto;
        background: #f2f2f2;
        overflow: hidden;
        background-size: cover;
        position: relative;

        img {
          width: 100%;
          height: 100%;
          border-radius: 0.5rem;
        }
      }
    }

    .article-list.member-article-list {
      background: #fff;
      margin: 10px;
      border-radius: 5px;
    }

    .posimg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;

      .van-icon-play,
      .van-icon-pause {
        font-size: 2.5rem;
        color: rgba(255, 255, 255, 86);
      }
    }
  }
</style>
